/*
 * @Author: lyx 2858535420@qq.com
 * @Date: 2022-10-10 22:31:07
 * @LastEditors: lyx 2858535420@qq.com
 * @LastEditTime: 2023-02-28 11:44:34
 * @FilePath: /antd-vue2-template/src/locales/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import moment from 'moment';

// default lang
import enUS from './lang/en-US';

Vue.use(VueI18n);

export const defaultLang = 'en-US';

const messages = {
  'en-US': {
    ...enUS
  }
};

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: defaultLang,
  fallbackLocale: defaultLang,
  messages
});

const loadedLanguages = [defaultLang];

function setI18nLanguage(lang) {
  i18n.locale = lang;
  // request.headers['Accept-Language'] = lang
  document.querySelector('html').setAttribute('lang', lang);
  return lang;
}

export function loadLanguageAsync(lang = defaultLang) {
  return new Promise(resolve => {
    // 缓存语言设置
    Vue.ls.set('lang', lang);
    if (i18n.locale !== lang) {
      if (!loadedLanguages.includes(lang)) {
        return import(/* webpackChunkName: "lang-[request]" */ `./lang/${lang}`).then(msg => {
          const locale = msg.default;
          i18n.setLocaleMessage(lang, locale);
          loadedLanguages.push(lang);
          moment.updateLocale(locale.momentName, locale.momentLocale);
          return setI18nLanguage(lang);
        });
      }
      return resolve(setI18nLanguage(lang));
    }
    return resolve(lang);
  });
}

export function i18nRender(key) {
  return i18n.t(`${key}`);
}

export default i18n;
